import React, { useState, useEffect } from 'react';
import {
  ArrowLeftOutlined,
  FileTextOutlined,
  EnvironmentOutlined,
  ClockCircleOutlined,
  UserOutlined
} from '@ant-design/icons';
import { Button, Tabs, Toast, Tag } from 'antd-mobile';
import { useNavigate, useParams } from 'react-router-dom';
import styles from './Order.module.css';

const DemoBlock = ({ title, padding, children }) => {
  return (
    <div className={styles.orderDemoBlock} style={{ padding }}>
      {title && <div className={styles.orderDemoBlockTitle}>{title}</div>}
      <div className={styles.orderDemoBlockContent}>{children}</div>
    </div>
  );
};

const OrderStatusTabs = ({ activeKey, onChange }) => {
  return (
    <DemoBlock title='' padding='0'>
      <Tabs
        activeKey={activeKey.toString()}
        onChange={(key) => onChange(Number(key))}
        swipeable={false}
      >
        <Tabs.Tab title='全部订单' key='0' />
        <Tabs.Tab title='待付款' key='1' />
        <Tabs.Tab title='待使用' key='2' />
        <Tabs.Tab title='待评价' key='3' />
        <Tabs.Tab title='已取消' key='4' />
      </Tabs>
    </DemoBlock>
  );
};

const OrderItem = ({ order, onCancel, onEvaluate, onInvoice, onDetail, onRebook }) => {
  const statusColorMap = {
    '待使用': { bgColor: '#E6F4FF', textColor: '#0958D9' },
    '待评价': { bgColor: '#F0F9EB', textColor: '#52C41A' },
    '已完成': { bgColor: '#F6FFED', textColor: '#238636' },
    '已取消': { bgColor: '#F5F5F5', textColor: '#8C8C8C' },
    '待付款': { bgColor: '#FFF1F0', textColor: '#CF1322' }
  };

  const { bgColor, textColor } = statusColorMap[order.status] || {
    bgColor: '#F5F5F5',
    textColor: '#8C8C8C'
  };
  
  return (
    <div className={styles.orderCard}>
      <div className={styles.orderHeader}>
        <span>
          <Tag
            color={bgColor}
            style={{
              '--text-color': textColor,
              '--border-radius': '10px',
              'padding': '3px 5px'
            }}
          >
            {order.status}
          </Tag>
        </span>
        <span className={styles.orderNo}>订单编号: {order.orderNo}</span>
        <span className={styles.orderTime}>{order.createTime}</span>
      </div>

      <div className={styles.orderContent}>
        <div className={styles.orderImg}>
          <img
            src={order.serviceImg}
            alt={order.serviceName}
            onError={(e) => e.target.src = 'https://picsum.photos/id/1005/80/80'}
            loading="lazy"
          />
        </div>
        <div className={styles.orderInfo}>
          <h3 className={styles.orderServiceName}>{order.serviceName}</h3>
          <div className={styles.orderInfoRow}>
            <EnvironmentOutlined className={styles.orderInfoIcon} />
            <span className={styles.orderInfoText}>{order.clinicName}</span>
          </div>
          <div className={styles.orderInfoRow}>
            <ClockCircleOutlined className={styles.orderInfoIcon} />
            <span className={styles.orderInfoText}>{order.serviceTime}</span>
          </div>
          <div className={styles.orderInfoRow}>
            <UserOutlined className={styles.orderInfoIcon} />
            <span className={styles.orderInfoText}>就诊人: {order.patientName}</span>
          </div>
        </div>
      </div>

      <div className={styles.orderFooter}>
        <div className={styles.orderPrice}>
          <span className={styles.orderPriceLabel}>实付款</span>
          <span className={styles.orderPriceValue}>¥{order.price}</span>
        </div>
        <div className={styles.orderActions}>
          {order.status === '待使用' && (
            <>
              <div
                className={`${styles.orderActionBtn} ${styles.orderCancelBtn}`}
                onClick={() => onCancel(order.id, order.serviceName)}
              >
                取消预约
              </div>
              <div
                className={`${styles.orderActionBtn} ${styles.orderDetailBtn}`}
                onClick={() => onDetail(order.id, order.serviceName)}
              >
                查看详情
              </div>
            </>
          )}

          {order.status === '待评价' && (
            <>
             
              <div
                className={`${styles.orderActionBtn} ${styles.orderEvaluateBtn}`}
                onClick={() => onEvaluate(order.id, order.serviceName)}
              >
                去评价
              </div>
            </>
          )}

          {order.status === '已完成' && (
            <>
             
              <div
                className={`${styles.orderActionBtn} ${styles.orderDetailBtn}`}
                onClick={() => onDetail(order.id, order.serviceName)}
              >
                查看详情
              </div>
            </>
          )}

          {order.status === '已取消' && (
            <div
              className={`${styles.orderActionBtn} ${styles.orderRebookBtn}`}
              onClick={() => onRebook(order.id, order.serviceName)}
            >
              重新预约
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

const Order = () => {
  const { tab } = useParams();
  const [activeTab, setActiveTab] = useState(tab ? parseInt(tab) : 0);
  const [orders, setOrders] = useState([]);
  const [filteredOrders, setFilteredOrders] = useState([]);
  const [loadingMore, setLoadingMore] = useState(false);
  const navigate = useNavigate();

  const mockOrders = [
    {
      id: 1,
      status: '待使用',
      orderNo: 'YL202308261589',
      createTime: '2023-08-26 10:23',
      serviceName: '全身推拿理疗',
      clinicName: '中医馆(总店)',
      serviceTime: '2023-08-26 14:30-15:30',
      patientName: '张先生',
      serviceImg: 'https://picsum.photos/id/177/80/80',
      price: 138
    },
    {
      id: 2,
      status: '待评价',
      orderNo: 'YL202308200956',
      createTime: '2023-08-20 08:15',
      serviceName: '肩颈专项调理',
      clinicName: '康泰中医诊所',
      serviceTime: '2023-08-20 15:00-16:00',
      patientName: '张先生',
      serviceImg: 'https://picsum.photos/id/1060/80/80',
      price: 108
    }, {
      id: 3,
      status: '已完成',
      orderNo: 'YL202308151324',
      createTime: '2023-08-15 11:30',
      serviceName: '艾灸温补调理',
      clinicName: '中医馆(总店)',
      serviceTime: '2023-08-15 16:30-17:30',
      patientName: '张先生',
      serviceImg: 'https://picsum.photos/id/237/80/80',
      price: 168
    },
    {
      id: 4,
      status: '已取消',
      orderNo: 'YL202308100845',
      createTime: '2023-08-10 09:12',
      serviceName: '腰椎推拿护理',
      clinicName: '仁和堂中医馆',
      serviceTime: '2023-08-12 10:00-11:00',
      patientName: '张先生',
      serviceImg: 'https://picsum.photos/id/287/80/80',
      price: 0
    },
    {
      id: 5,
      status: '待付款',
      orderNo: 'YL202308281123',
      createTime: '2023-08-28 10:45',
      serviceName: '头部放松按摩',
      clinicName: '康泰中医诊所',
      serviceTime: '2023-08-29 09:30-10:30',
      patientName: '张先生',
      serviceImg: 'https://picsum.photos/id/337/80/80',
      price: 88
    }
  ];

  useEffect(() => {
    setOrders(mockOrders);
    filterOrdersByTab(activeTab, mockOrders);
  }, [activeTab]);

  useEffect(() => {
    if (tab) {
      const tabNum = parseInt(tab);
      if (!isNaN(tabNum) && tabNum >= 0 && tabNum <= 4) {
        setActiveTab(tabNum);
      }
    }
  }, [tab]);

  const filterOrdersByTab = (tabIndex, orderList) => {
    let result = [...orderList];
    switch (tabIndex) {
      case 1:
        result = orderList.filter(order => order.status === '待付款');
        break;
      case 2:
        result = orderList.filter(order => order.status === '待使用');
        break;
      case 3:
        result = orderList.filter(order => order.status === '待评价');
        break;
      case 4:
        result = orderList.filter(order => order.status === '已取消');
        break;
      default:
        break;
    }
    setFilteredOrders(result);
  };

  useEffect(() => {
    if (tab !== activeTab.toString()) {
      navigate(`/order/${activeTab}`);
    }
  }, [activeTab, navigate, tab]);

  const handleCancelOrder = (orderId, serviceName) => {
    Toast.confirm(`确定要取消「${serviceName}」的预约吗？`, {
      confirmText: '确定',
      cancelText: '取消',
      onConfirm: () => {
        const updatedOrders = orders.map(order =>
          order.id === orderId ? { ...order, status: '已取消' } : order
        );
        setOrders(updatedOrders);
        filterOrdersByTab(activeTab, updatedOrders);
        Toast.show('预约已取消');
      }
    });
  };

  const handleEvaluateOrder = (orderId, serviceName) => {
    navigate('/order/evaluation');
  };


  const handleDetailOrder = (orderId, serviceName) => {
    navigate('/order/orderdetail');
  };

  const handleRebookOrder = (orderId, serviceName) => {
    Toast.show(`重新预约「${serviceName}」`);
  };

  const handleLoadMore = () => {
    setLoadingMore(true);
    setTimeout(() => {
      const newOrders = [
        {
          id: 6,
          status: '已完成',
          orderNo: 'YL202308050678',
          createTime: '2023-08-05 14:40',
          serviceName: '足部理疗按摩',
          clinicName: '中医馆(分店)',
          serviceTime: '2023-08-05 16:00-17:00',
          patientName: '张先生',
          serviceImg: 'https://picsum.photos/id/301/80/80',
          price: 98
        },
        {
          id: 7,
          status: '已完成',
          orderNo: 'YL202307280456',
          createTime: '2023-07-28 09:15',
          serviceName: '背部经络疏通',
          clinicName: '康泰中医诊所',
          serviceTime: '2023-07-28 10:30-11:30',
          patientName: '张先生',
          serviceImg: 'https://picsum.photos/id/306/80/80',
          price: 128
        }
      ];
      const updatedOrders = [...orders, ...newOrders];
      setOrders(updatedOrders);
      filterOrdersByTab(activeTab, updatedOrders);
      setLoadingMore(false);
      Toast.show('已加载更多订单');
    }, 1500);
  };

  return (
    <div className={styles.myOrdersPage}>
      <header className={styles.ordersHeader}>
        <i className="fa fa-arrow-left"  style={{ color: '#8B5A2B', fontSize: '20px',cursor:'pointer' }} onClick={() => navigate("/me")}></i>
        <h1 className={styles.orderHeaderTitle}>我的订单</h1>
        <div></div>
      </header>

      <OrderStatusTabs
        activeKey={activeTab}
        onChange={(key) => setActiveTab(key)}
      />

      <main className={styles.ordersContent}>
        {filteredOrders.length > 0 ? (
          <div className={styles.ordersList}>
            {filteredOrders.map(order => (
              <OrderItem
                key={order.id}
                order={order}
                onCancel={handleCancelOrder}
                onEvaluate={handleEvaluateOrder}
                onDetail={handleDetailOrder}
                onRebook={handleRebookOrder}
              />
            ))}
          </div>
        ) : (
          <div className={styles.orderEmptyOrders}>
            <div className={styles.orderEmptyIcon}>
              <FileTextOutlined style={{ fontSize: '48px', color: '#D7CCC8' }} />
            </div>
            <p className={styles.orderEmptyText}>暂无相关订单</p>
            <Button
              className={styles.orderEmptyBtn}
              onClick={() => setActiveTab(0)}
            >
              查看全部订单
            </Button>
          </div>
        )}

        {filteredOrders.length > 0 && (
          <div className={styles.orderLoadMoreContainer}>
            <Button
              className={styles.orderLoadMoreBtn}
              onClick={handleLoadMore}
              disabled={loadingMore}
            >
              {loadingMore ? '加载中...' : '加载更多'}
            </Button>
          </div>
        )}
      </main>
    </div>
  );
};

export default Order;
    